package com.example.demo.dao;

import com.example.demo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Types;
import java.util.List;

@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public int add(Student student) {
        // 方式一
//        String sql = "insert into student(name,sex) values(?,?)";
//        Object[] args = {student.getName(),student.getSex()};
//        int[] argTypes = {Types.VARCHAR,Types.VARCHAR};
//        return this.jdbcTemplate.update(sql,args,argTypes);

        String sql = "insert into student(name,sex) values(:name,:sex)";
        NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
        return npjt.update(sql, new BeanPropertySqlParameterSource(student));
    }

    @Override
    public int update(Student student) {
        String sql = "update student set name = ?,sex = ? where id = ?";
        Object[] args = { student.getName(), student.getSex(), student.getId() };
        int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
        return this.jdbcTemplate.update(sql, args, argTypes);
    }

    @Override
    public int deleteByid(Integer id) {
        String sql = "delete from student where id = ?";
        Object[] args = { id };
        int[] argTypes = { Types.VARCHAR };
        return this.jdbcTemplate.update(sql, args, argTypes);
    }

//    @Override
//    public List<Map<String, Object>> queryStudentsListMap() {
//        String sql = "select * from student";
//        return this.jdbcTemplate.queryForList(sql);
//    }

    @Override
    public Student queryStudentByid(Integer id) {
        String sql = "select * from student where id = ?";
        Object[] args = { id };
        int[] argTypes = { Types.VARCHAR };
        List<Student> studentList = this.jdbcTemplate.query(sql, args, argTypes, new StudentMapper());
        if (studentList != null && studentList.size() > 0) {
            return studentList.get(0);
        } else {
            return null;
        }
    }
}
